package com.atguigu.gmall;

import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * @author: atguigu
 * @create: 2023-01-03 15:36
 */
public class CompletableFutureFallBackDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int processors = Runtime.getRuntime().availableProcessors();
        System.out.println(processors + 1);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(processors,
                processors,
                10, TimeUnit.SECONDS
                , new ArrayBlockingQueue<>(3)
                , Executors.defaultThreadFactory());


        //1.创建CompletableFuture异步任务对象
        //1.1 支持获取线程计算结果
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread() + ",supplyAsync:");
            int i = 1/0;
            return "atguigu";
        }, executor);

        future = future.exceptionally((e) -> {
            //设置异常回调
            System.out.println(Thread.currentThread() + ",exceptionally:" + e);
            return "666";
        });
        //给异步对象设置回调方法 whenComplete既可以处理异步任务正常情况，异常情况
        //future.whenCompleteAsync((t, e) -> {
        //    System.out.println(Thread.currentThread() + ",whenComplete:" + t);
        //    if (e != null) {
        //        e.printStackTrace();
        //    }
        //});
        future.join();
        String result = future.get();
        System.out.println(result);


        executor.shutdown();
    }
}
